package leetcode.D300.T227;

import java.util.Deque;
import java.util.LinkedList;

class Solution {
    public int calculate(String s) {
        s = s + "+";
        Deque<Integer> dq = new LinkedList<>();
        int curNum = 0, result = 0, lastOp = 0, tempOp = 2, base = 1;
        boolean flag = false;
        for(int i=0; i<s.length(); ++i) {
            char c = s.charAt(i);
            if(c == ' ') continue;
            if(Character.isDigit(c)) {
                curNum = curNum * 10 + (c - '0');
            } else {
                if(c == '+' || c == '-') {
                    if(flag) {
                        curNum = tempOp == 2 ? curNum*base : base/curNum;
                        flag = false;
                    }
                    if(lastOp == 0) result += curNum;
                    else result -= curNum;
                    lastOp = c == '+' ? 0 : 1;
                } else {
                    if(flag) {
                        base = tempOp == 2 ? curNum*base : base/curNum;
                    } else {
                        flag = true;
                        base = curNum;
                    }
                    tempOp = c == '*' ? 2 : 3;
                }
                curNum = 0;
            }
        }
        return result;
    }
}